<template>
  <div class="login_container">
    <!-- 头部区域 -->
    <div class="login_cont">
      <!-- 标题 -->
      <h2 class="login_cont_title">后台电商管理登录</h2>
      <!-- 登录信息 -->
      <el-form class="login_formOk" ref="loginFormRef" :model="loginForm" :rules="loginRules">
        <!-- 用户名 -->
        <el-form-item prop="username">
          <el-input placeholder="用户名" prefix-icon="el-icon-user-solid" v-model="loginForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input placeholder="密码" prefix-icon="el-icon-lock" v-model="loginForm.password"></el-input>
        </el-form-item>

        <!-- 登录和重置 -->
        <el-form-item class="itembtn">
          <el-button type="primary" @click="addLogin">确认</el-button>
          <el-button type="info" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      // 收集表单的数据
      loginForm: {
        username: '',
        password: ''
      },
      // 表单的验证规则对象
      loginRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 12, message: '长度在 3 到 12 个字符之间', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 提交按钮  发起post请求提交
    addLogin() {
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请先填选项')
        const { data: res } = await this.$http.post('login', this.loginForm)
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败！')
        }
        this.$message.success('登录成功!')
        // 登录成功 生成token值 和跳转后台主页路由
        window.sessionStorage.setItem('token', res.data.token)
        this.$router.push('/home')
      })
    },
    reset() {
      this.$refs.loginFormRef.resetFields()
    }
  }
}
</script>
<style lang="less" scoped>
.login_container {
  position: relative;
  height: 100%;
  background-color: #41b883;
  .login_cont {
    width: 520px;
    height: 320px;
    background-color: #f2f2f2;
    border-radius: 18px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    .login_cont_title {
      text-align: center;
      height: 60px;
    }
    .login_formOk {
      width: 100%;
      padding: 0 50px;
      box-sizing: border-box;
      .el-input__inner {
        height: 50px;
        font-size: 16px;
      }
    }
  }
}
.itembtn {
  display: flex;
  justify-content: flex-end;
}
</style>
